import cv2
import matplotlib.pyplot as plt  # hist直方图需要使用matplotlib进行展示

img = cv2.imread('../week2/pic2.png')
img2 = cv2.imread('../week2/pic6.png')

# 灰度直方图展示，使用matplotlib的hist
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
gray2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
# # gray.ravel（）  将gray展平
plt.ion()
plt.hist(gray.ravel(), 256, [0, 256])
plt.show()
plt.hist(gray2.ravel(), 256, [0, 256])
plt.show()


mblur = cv2.medianBlur(gray, 7)  # 使用中值滤波平滑脉冲噪声
_, img_1 = cv2.threshold(mblur, 0, 255, cv2.THRESH_OTSU)   # 使用大津算法,
mblur2 = cv2.medianBlur(gray2, 7)
_, img_2 = cv2.threshold(mblur2, 0, 255, cv2.THRESH_OTSU)
cv2.imshow('img_1', img_1)
cv2.imshow('img_2', img_2)
cv2.waitKey()
